const app = getApp();
const formatTime = (date, sign=0, showTime=false)=> {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join(['/', '-'][sign])}${!showTime && ' ' + [hour, minute, second].map(formatNumber).join(':') || ''}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const colorRgba = (sHex, alpha = 1) => {
  // 十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  /* 16进制颜色转为RGB格式 */
  let sColor = sHex.toLowerCase()
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    //  处理六位的颜色值
    var sColorChange = []
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(i, i + 2)))
    }
    return 'rgba(' + sColorChange.join(',') + ',' + alpha + ')'
  } else {
    return sColor
  }
}

// 计算秒
let countS = (data, time) => {
  let new_D = [];
  data.forEach(item => {
    new_D.push(item / time)
  })
  return new_D
}

let getTimeStm = (d) => {
  return new Date(d.split('-').join('/')).getTime()
}

let goLogin = () => {
  wx.reLaunch({
    url: '/pages/login/login',
  })
  wx.clearStorageSync('token')
  wx.clearStorageSync('username')
  wx.clearStorageSync('moduleList')
  wx.clearStorageSync('moduleConfig')
  wx.clearStorageSync('radioChange')
  wx.setStorageSync('canRequest', true)
  clearTimeout(app.globalData.timer)
}
let colorTwo = function (val) {
  switch (val) {
    case '红': return 'rgba(255,92,92,1)';
      break;
    case '黄': return 'rgba(255,249,75,1)';
      break;
    case '蓝': return 'rgba(92,255,240,1)';
      break;
    case '青': return 'rgba(99,224,255,1)';
      break;
    case '浅黄': return 'rgba(238,153,34,1)';
      break;
    case '紫': return 'rgba(79,66,251,1)';
      break;
  }
}
let fill0 = val => val < 10 ? '0' + val : val + '';
// 计算实际加工时间
let timeFormat = function(val) {
  if (isNaN(val) || Number(val) === 0) return `00h 00m 00s`;
  let timestamp = Number(val) / 1000;
  let h = Math.floor(timestamp / 3600),
    m = Math.floor((timestamp % 3600) / 60),
    s = Math.floor(timestamp % 60);
  return `${fill0(h)}h ${fill0(m)}m ${fill0(s)}s`;
}

module.exports = {
  formatTime: formatTime,
  formatNumber: formatNumber,
  colorRgba,
  countS,
  getTimeStm,
  goLogin,
  colorTwo,
  timeFormat
}
